<?php

namespace app\common\controller;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Controller;
use think\Request;
require_once VENDOR_PATH . 'firebase/php-jwt/src/JWT.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/SignatureInvalidException.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/BeforeValidException.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/ExpiredException.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/Key.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/CachedKeySet.php';
require_once VENDOR_PATH . 'firebase/php-jwt/src/JWK.php';
/**
 * 公共资源-苹果类
 */
class Appstore extends Controller
{

    /**
     * 苹果退款验证
     * @param string $inputStr 退款信息
     * @return \think\Response
     */
    public function refundOrder($inputStr = '')
    {
        $input = empty($inputStr) ? file_get_contents('php://input') : $inputStr;
        write_log('INFO', 'Notify.php', '退款:'.$input, 'apple', true);
        $data = json_decode($input, true);

        $payload_json = $this->decodePayNotifyV2($data['signedPayload']);
        if (empty($payload_json) || !isset($payload_json['data'])) {
            return;
        }

        $payload_json['data'] = get_object_vars($payload_json['data']);
        $t_payload_json = $this->decodePayNotifyV2($payload_json['data']['signedTransactionInfo']);

        if (empty($t_payload_json) || empty($t_payload_json['transactionId'])) {
            return;
        }

        $vals = $t_payload_json;
        $vals['notificationType'] = $payload_json['notificationType'];
        $vals['notificationUUID'] = $payload_json['notificationUUID'];
        $vals['appAppleId'] = $payload_json['data']['appAppleId'];
        $vals['bundleVersion'] = $payload_json['data']['bundleVersion'];
        $vals['version'] = $payload_json['version'];

        $vals['purchaseDate'] = date('Y-m-d H:i:s', substr($vals['purchaseDate'], 0, 10));
        $vals['originalPurchaseDate'] = date('Y-m-d H:i:s', substr($vals['originalPurchaseDate'], 0, 10));
        $vals['signedDate'] = date('Y-m-d H:i:s', substr($vals['signedDate'], 0, 10));

        if (isset($vals['revocationDate'])) {
            $vals['revocationDate'] = date('Y-m-d H:i:s', substr($vals['revocationDate'], 0, 10));
        }

        return $vals;
    }

    public function createPublicKey($rsaKeyStr)
    {
        $rsaKeyPem = '';

        $beginPublicKey = '-----BEGIN CERTIFICATE-----';
        $endPublicKey = '-----END CERTIFICATE-----';

        $rsaKeyPem .= $beginPublicKey . "\n";
        $rsaKeyPem .= wordwrap($rsaKeyStr, 64, "\n", true) . "\n";
        $rsaKeyPem .= $endPublicKey;

        if (!function_exists('openssl_pkey_get_public')) {
            return false;
        }

        if (false == openssl_pkey_get_public($rsaKeyPem)) {
            return false;
        }

        return $rsaKeyPem;
    }

    public function decodePayNotifyV2($jwt)
    {
        list($header, $payload, $sign) = explode('.', $jwt);
        $header_decode = base64_decode($header);
        $header_json = json_decode($header_decode, true);

        if (!isset($header_json['x5c'])) {
            return false;
        }

        //这一步是将公钥转成对应的格式
        $pubkey = $this->createPublicKey($header_json['x5c'][0]);
        try {
            $decoded = JWT::decode($jwt, new Key($pubkey, $header_json['alg']));
        } catch (\UnderflowException $e) {
            return false;
        }
        return get_object_vars($decoded);
    }
}
